package com.xncoding.freemarker.ctr;

import java.io.IOException;
import java.util.*;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.export.ExcelExportService;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xncoding.freemarker.base.ErrorCode;
import com.xncoding.freemarker.model.ColumnClass;
//import com.xncoding.freemarker.service.SwServiceImpl;
import com.xncoding.freemarker.utile.FtpUtil;
import com.xncoding.starter.inter.GlobalProperConfig;
import com.xncoding.starter.service.ExampleService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/t1")
public class HelloPageCtrler {
//    @Autowired
//    SwServiceImpl sw;
    @Autowired
    GlobalProperConfig transcodepro;
    @Autowired
    private MessageSource messageSource;
    @Autowired
    private ExampleService exampleService;
    @Autowired
    private FtpUtil ftpUtil;

    @GetMapping("/t1")
    public String toHelloPage(ModelMap modelMap) {
        Map<String, String> map = new HashMap<>();
        map.put("name", "中文姓名");
        map.put("address", "看看中文地址是否正常");
        modelMap.addAttribute("userInfo", map);
        return "hello";//freemarker模板文件路径（没有文件路径，默认src/main/resources/templates目录）
    }

    @PostMapping("/t2")
    public String t2(@RequestBody ColumnClass cla) {
        System.out.println(JSON.toJSONString(cla));
        System.out.println("aaaaaa:"+transcodepro.getConfig("HH1101"));;
        System.out.println(ErrorCode.PAY_ERROR);
        System.out.println(messageSource.getMessage("HH1101",null,Locale.getDefault()));
        System.out.println(exampleService.wrap("你猜猜"));;
        return "hello1";//freemarker模板文件路径（没有文件路径，默认src/main/resources/templates目录）
    }

    @PostMapping("/a1")
    public String a1(@RequestBody ColumnClass columnClass) {
        System.out.println("a1:"+JSON.toJSONString(columnClass));
        return "hello1";//freemarker模板文件路径（没有文件路径，默认src/main/resources/templates目录）
    }

    @RequestMapping("/api")
    public void api(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=111.xls");

//        String s = HttpUtil.get("http://10.3.20.61:18191/ebank/actuator/eos/v2/api-docs");
        String s = HttpUtil.get("http://10.3.20.61:18292/mpbank/actuator/eos/v2/api-docs");
//        String s = HttpUtil.get("http://127.0.0.1:18191/ebank/actuator/eos/v2/api-docs");
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONObject paths = jsonObject.getJSONObject("paths");
        JSONObject definitions = jsonObject.getJSONObject("definitions");

        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String>[] h1 = new Map[]{null};

        List<Map<String, Object>> allList = new ArrayList<>();

        paths.keySet().stream().forEach(x -> {
            System.err.println("接口地址====" + x);
            System.err.println("功能名称====" + paths.getJSONObject(x).getJSONObject("post").getJSONArray("tags").get(0).toString());
            System.err.println("接口名称====" + paths.getJSONObject(x).getJSONObject("post").getString("summary"));

            h1[0] = new HashMap<String,String>();

            h1[0].put("jkdz", x);
            h1[0].put("jkmc", paths.getJSONObject(x).getJSONObject("post").getString("summary"));
            h1[0].put("mnmc", paths.getJSONObject(x).getJSONObject("post").getJSONArray("tags").get(0).toString());

            list.add(h1[0]);
//            allList.add((Map<String, Object>) list);

            Optional.ofNullable(paths.getJSONObject(x).getJSONObject("post").getJSONArray("parameters"))
                    .ifPresent(y -> {
                        JSONObject a = (JSONObject) y.get(0);
                        System.out.println(y.get(0).toString());
                        Optional.ofNullable(a.getJSONObject("schema")).ifPresent(z -> {
                            System.out.println(JSON.toJSONString(z));
                            Optional<String> name = Optional.ofNullable(z.getString("$ref"));
                            if(name.isPresent()){
                                Optional<JSONObject> param = Optional.ofNullable(definitions.getJSONObject(z.getString("$ref").replaceAll("#/definitions/","")));
                                if(param.isPresent()){
                                    List<Map<String, Object>> filelist = new ArrayList<Map<String, Object>>();

                                    Optional.ofNullable(param.get().getJSONObject("properties")).ifPresent(c -> {
                                        System.err.println("入参开始@@@@@@@@@@@@@@@@@");
                                        final Map<String, Object>[] fiedMap = new Map[]{null};
                                        c.keySet().stream().forEach(v -> {
                                            System.err.println("字段名称======" + v);
                                            System.err.println("字段类型======" + c.getJSONObject(v).getString("type"));
                                            System.err.println("字段中文名称======" + c.getJSONObject(v).getString("description"));
                                            fiedMap[0] = new HashMap<String,Object>();
                                            fiedMap[0].put("zdmc",v);
                                            fiedMap[0].put("zdlx",c.getJSONObject(v).getString("type"));
                                            fiedMap[0].put("zdzwmc",c.getJSONObject(v).getString("description"));
                                            filelist.add(fiedMap[0]);
                                        });
                                    });
                                    allList.addAll(filelist);

                                }
                                System.err.println();
                            }
                        });
                    });


        });

        // 将sheet1、sheet2使用得map进行包装
        List<Map<String, Object>> sheetsList = new ArrayList<>();


        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();//构造对象等同于@Excel
        entity.add(new ExcelExportEntity("功能名称", "mnmc"));
        entity.add(new ExcelExportEntity("接口名称", "jkmc"));
        entity.add(new ExcelExportEntity("接口地址", "jkdz"));

        Map<String, Object> sheet1ExportMap = new HashMap<>();
        sheet1ExportMap.put(NormalExcelConstants.CLASS, ExcelExportEntity.class);
        sheet1ExportMap.put(NormalExcelConstants.DATA_LIST, list);
        sheet1ExportMap.put(NormalExcelConstants.PARAMS, new ExportParams("遥信表", "遥信"));
        //这边为了方便，sheet1和sheet2用同一个表头(实际使用中可自行调整)
        sheet1ExportMap.put(NormalExcelConstants.MAP_LIST, entity);
        sheetsList.add(sheet1ExportMap);


        List<ExcelExportEntity> filedEntity = new ArrayList<ExcelExportEntity>();//构造对象等同于@Excel
        filedEntity.add(new ExcelExportEntity("字段名称", "zdmc"));
        filedEntity.add(new ExcelExportEntity("字段类型", "zdlx"));
        filedEntity.add(new ExcelExportEntity("字段中文名称", "zdzwmc"));

        for (int i = 0;i< allList.size();i++){
            Map<String, Object> sheet2ExportMap = new HashMap<>();
            sheet2ExportMap.put(NormalExcelConstants.CLASS, ExcelExportEntity.class);
            sheet2ExportMap.put(NormalExcelConstants.DATA_LIST, allList.get(i));
            sheet2ExportMap.put(NormalExcelConstants.PARAMS, new ExportParams("遥信表"+i, "遥信"+i));
            //这边为了方便，sheet1和sheet2用同一个表头(实际使用中可自行调整)
            sheet2ExportMap.put(NormalExcelConstants.MAP_LIST, filedEntity);
            sheetsList.add(sheet2ExportMap);
        }

        Workbook workbook = new HSSFWorkbook();
        for(Map<String,Object> map : sheetsList) {
            ExcelExportService server = new ExcelExportService();
            ExportParams param = (ExportParams) map.get("params");
            @SuppressWarnings("unchecked")
            List<ExcelExportEntity> mapList = (List<ExcelExportEntity>) map.get("mapList");
            Collection<?> data = (Collection<?>) map.get("data");
            server.createSheetForMap(workbook, param, entity, data);
        }

        workbook.write(response.getOutputStream());
    }


    @RequestMapping("/api2")
    public void api2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=111.xls");

        String s = HttpUtil.get("http://10.3.20.61:18291/mbank/actuator/eos/v2/api-docs");
//        String s = HttpUtil.get("http://127.0.0.1:18191/ebank/actuator/eos/v2/api-docs");
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONObject paths = jsonObject.getJSONObject("paths");
        JSONObject definitions = jsonObject.getJSONObject("definitions");

        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String>[] h1 = new Map[]{null};

        List<Map<String, Object>> allList = new ArrayList<>();


        // 将sheet1、sheet2使用得map进行包装
        List<Map<String, Object>> sheetsList = new ArrayList<>();

        List<ExcelExportEntity> filedEntity = new ArrayList<ExcelExportEntity>();//构造对象等同于@Excel
        filedEntity.add(new ExcelExportEntity("字段名称", "zdmc"));
        filedEntity.add(new ExcelExportEntity("字段类型", "zdlx"));
        filedEntity.add(new ExcelExportEntity("字段中文名称", "zdzwmc"));

        paths.keySet().stream().forEach(x -> {
            String jkmc = paths.getJSONObject(x).getJSONObject("post").getString("summary");
            String jkdz = x;

            Optional<JSONObject> param = Optional.ofNullable(definitions.getJSONObject(jkmc));
            if(param.isPresent()){
                List<Map<String, Object>> filelist = new ArrayList<Map<String, Object>>();

                Optional.ofNullable(param.get().getJSONObject("properties")).ifPresent(c -> {
                    System.err.println("入参开始@@@@@@@@@@@@@@@@@");
                    final Map<String, Object>[] fiedMap = new Map[]{new HashMap<>()};
                    c.keySet().forEach(v -> {
                        System.err.println("字段名称======" + v);
                        System.err.println("字段类型======" + c.getJSONObject(v).getString("type"));
                        System.err.println("字段中文名称======" + c.getJSONObject(v).getString("description"));
                        fiedMap[0] = new HashMap<String,Object>();
                        fiedMap[0].put("zdmc",v);
                        fiedMap[0].put("zdlx",c.getJSONObject(v).getString("type"));
                        fiedMap[0].put("zdzwmc",c.getJSONObject(v).getString("description"));
                        filelist.add(fiedMap[0]);

                    });

                    Map<String, Object> sheet2ExportMap = new HashMap<>();
                    sheet2ExportMap.put(NormalExcelConstants.CLASS, ExcelExportEntity.class);
                    sheet2ExportMap.put(NormalExcelConstants.DATA_LIST, filelist);
                    sheet2ExportMap.put(NormalExcelConstants.PARAMS, new ExportParams(jkmc, jkmc));
                    //这边为了方便，sheet1和sheet2用同一个表头(实际使用中可自行调整)
                    sheet2ExportMap.put(NormalExcelConstants.MAP_LIST, filedEntity);
                    sheetsList.add(sheet2ExportMap);
                });
            }
        });



        Workbook workbook = new HSSFWorkbook();
        for(Map<String,Object> map : sheetsList) {
            ExcelExportService server = new ExcelExportService();
            ExportParams param = (ExportParams) map.get("params");

//            List<ExcelExportEntity> mapList = (List<ExcelExportEntity>) map.get("mapList");
//            Collection<?> data = Collections.singleton(map.get("data"));
            Collection<?> data = (Collection<?>) map.get("data");
            server.createSheetForMap(workbook, param, filedEntity, data);
        }

        workbook.write(response.getOutputStream());
    }


    @RequestMapping("api3")
    public void expoeMoreSheet01(HttpServletRequest request, HttpServletResponse response) throws Exception {

        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=ReMianPage.xls");
        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();//构造对象等同于@Excel

        entity.add(new ExcelExportEntity("性别", "sex"));
        entity.add(new ExcelExportEntity("姓名", "name"));

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String,Object> h1 = new HashMap<String,Object>();
        h1.put("name", "你大爷");
        h1.put("sex", "男");
        Map<String,Object> h2 = new HashMap<String,Object>();
        h2.put("name", "你打奶");
        h2.put("sex", "女");
        list.add(h1);
        list.add(h2);

        List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
        Map<String,Object> h3 = new HashMap<String,Object>();
        h3.put("name", "你大爷");
        h3.put("sex", "男");
        Map<String,Object> h4 = new HashMap<String,Object>();
        h4.put("name", "你打奶");
        h4.put("sex", "女");
        list1.add(h3);
        list1.add(h4);

        // sheet1设置
        Map<String, Object> sheet1ExportMap = new HashMap<>();
        sheet1ExportMap.put(NormalExcelConstants.CLASS, ExcelExportEntity.class);
        sheet1ExportMap.put(NormalExcelConstants.DATA_LIST, list);
        sheet1ExportMap.put(NormalExcelConstants.PARAMS, new ExportParams("遥信表", "遥信"));
        //这边为了方便，sheet1和sheet2用同一个表头(实际使用中可自行调整)
        sheet1ExportMap.put(NormalExcelConstants.MAP_LIST, entity);

        //Sheet2设置
        Map<String, Object> sheet2ExportMap = new HashMap<>();
        sheet2ExportMap.put(NormalExcelConstants.CLASS, ExcelExportEntity.class);
        sheet2ExportMap.put(NormalExcelConstants.DATA_LIST, list1);
        sheet2ExportMap.put(NormalExcelConstants.PARAMS, new ExportParams("遥测表", "遥测"));
        //这边为了方便，sheet1和sheet2用同一个表头(实际使用中可自行调整)
        sheet2ExportMap.put(NormalExcelConstants.MAP_LIST, entity);

        // 将sheet1、sheet2使用得map进行包装
        List<Map<String, Object>> sheetsList = new ArrayList<>();
        sheetsList.add(sheet1ExportMap);
        sheetsList.add(sheet2ExportMap);
        Workbook workbook = new HSSFWorkbook();
        for(Map<String,Object> map : sheetsList) {
            ExcelExportService server = new ExcelExportService();
            ExportParams param = (ExportParams) map.get("params");
            @SuppressWarnings("unchecked")
            List<ExcelExportEntity> mapList = (List<ExcelExportEntity>) map.get("mapList");
            Collection<?> data = (Collection<?>) map.get("data");
            server.createSheetForMap(workbook, param, entity, data);
        }

        //把我们构造好的bean对象放到params就可以了
//        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("测试11", "测试22"), entity,
//                list);
        workbook.write(response.getOutputStream());
    }


    @RequestMapping("/api4")
    public void api4(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=111.xls");


    }


    @PostMapping("/t01")
    public String t1() {
        maopao();
        return "hello";
    }

    @PostMapping("/t02")
    public String t2() {
        Random r = new Random();
        int i1 = r.nextInt(50);
        int res = Wayone(i1);
        return String.valueOf(res);
    }
    public  static String maopao(){
        Random random = new Random();
        int[] arr  = random.ints(10000).toArray();//{18,13,50,15,4,17,18};

        int temp  = 0 ;
        for(int i = 0 ;i< arr.length -1; i++){
            for(int j = 0; j<arr.length-1-i; j++){
                if(arr[j]>arr[j+1]){
                    temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }

        }
        return "";
    }

    /**
     * 普通的循环方法求阶乘
     * @param num
     * @return
     */
    public static int Wayone(int num) {
        int sum=1;
        if(num<0) {
            throw new IllegalArgumentException("需要计算的参数必须为正数！");//抛出不合理参数异常
        }
        for(int i=1;i<=num;i++) {
            sum*=i;
        }
        return sum;
    }

}
